﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Http;
using BaseBll;
using BaseWebApi.App_Start;
using BaseWebApi.Common;
using BaseWebApi.Models;
using Common;
using Models;

namespace BaseWebApi.Controllers
{
    /// <summary>
    /// 付款申请
    /// </summary>
    [ControllerGroup(groupName: "PurchasePayApply", useage: "采购管理-付款申请")]
    public class PurchasePayApplyController : BaseController
    {
        private JWTPlayloadInfo playload;
        private readonly PurchasePayApplyBll _instance = PurchasePayApplyBll.Instance;

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="pageIndex">当前页</param>
        /// <param name="pageSize">页尺寸</param>
        /// <param name="number">付款编号</param>
        /// <param name="person">申请人员</param>
        /// <param name="deptId">部门id</param>
        /// <param name="auditStatus">工单状态</param>
        /// <param name="date">申请时间</param>
        /// <param name="supplierName">供应商</param>
        /// <returns></returns>
        [HttpGet]
        public HttpResponseMessage GetPageList(int pageIndex=1, int pageSize=10, string number = "", string person = "", int deptId = 0, int auditStatus = -1, string date = "", string supplierName = "")
        {
            StringBuilder strWhere = new StringBuilder("");
            if (!string.IsNullOrEmpty(number))
            {
                strWhere.Append(" and PPA_Number like '%" + number + "%'");
            }
            if (!string.IsNullOrEmpty(person))
            {
                strWhere.Append(" and PPA_Person like '%" + person + "%'");
            }
            if (deptId != 0)
            {
                strWhere.Append(" and PPA_DeptId = " + deptId);
            }
            if (auditStatus != -1)
            {
                strWhere.Append(" and PPA_AuditStatus = " + auditStatus);
            }
            if (!string.IsNullOrEmpty(date))
            {
                // 判断是否是日期格式
                if (DateTime.TryParse(date, out DateTime parsedDate))
                {
                    strWhere.Append(" and PPA_Date = '" + date + "'");
                }
                else
                {                  
                    return JsonHelper.ErrorJson("无效的日期格式");
                }
            }
            if (!string.IsNullOrEmpty(supplierName))
            {
                strWhere.Append(" and PO_SupplierName like '%" + supplierName + "%'");
            }

            DataTable dt = _instance.GetPageList(pageSize, pageIndex, strWhere.ToString(), "PPA_Date DESC", out int records);
            int totalPages = PageHelper.GetPageCount(pageSize, records);
            return JsonHelper.SuccessJson(CommonOperation.DataTable2JArray(dt), pageIndex, totalPages, records);
        }

        /// <summary>
        /// 查询付款申请（不分页）
        /// </summary>
        /// <param name="number"></param>
        /// <param name="person"></param>
        /// <param name="deptId"></param>
        /// <param name="auditStatus"></param>
        /// <param name="date"></param>
        /// <param name="supplierName"></param>
        /// <returns></returns>
        [HttpGet]
        public HttpResponseMessage GetList(string number = "", string person = "", int deptId = 0, int auditStatus = -1, string date = "", string supplierName = "")
        {
            StringBuilder strWhere = new StringBuilder("");
            if (!string.IsNullOrEmpty(number))
            {
                strWhere.Append(" and PPA_Number like '%" + number + "%'");
            }
            if (!string.IsNullOrEmpty(person))
            {
                strWhere.Append(" and PPA_Person like '%" + person + "%'");
            }
            if (deptId != 0)
            {
                strWhere.Append(" and PPA_DeptId = " + deptId);
            }
            if (auditStatus != -1)
            {
                strWhere.Append(" and PPA_AuditStatus = " + auditStatus);
            }
            if (!string.IsNullOrEmpty(date))
            {
                // 判断是否是日期格式
                if (DateTime.TryParse(date, out DateTime parsedDate))
                {
                    strWhere.Append(" and PPA_Date = '" + date + "'");
                }
                else
                {
                    return JsonHelper.ErrorJson("无效的日期格式");
                }
            }
            if (!string.IsNullOrEmpty(supplierName))
            {
                strWhere.Append(" and PPA_SupplierName like '%" + supplierName + "%'");
            }

            List<PurchasePayApplyHead> list = _instance.GetList(strWhere.ToString());

            return JsonHelper.SuccessJson(JsonHelper.ListToJArray(list));
        }

        /// <summary>
        /// 根据ID获取实体对象
        /// </summary>
        /// <param name="ID">数据表ID</param>
        /// <returns></returns>
        [HttpGet]
        public HttpResponseMessage GetModel(int ID)
        {
            if (ID > 0)
            {
                PurchasePayApplyHead model = _instance.GetModelById(ID);
                if (model != null)
                {
                    // 查询文件
                    DataTable dt = UploadBll.Instance.GetFiles(ID, "PurchasePayApply");
                    model.FileList = CommonOperation.ConvertDataTableToModelList<FileData>(dt);
                    return JsonHelper.SuccessJson(JsonHelper.ModelToJObject(model));
                }
                else
                {
                    return JsonHelper.FailJson("数据不存在");
                }
            }
            else
            {
                return JsonHelper.FailJson("参数错误");
            }
        }

        /// <summary>
        /// 新增付款申请
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public HttpResponseMessage AddPurchasePayApply([FromBody] PurchasePayApplyHead model)
        {
            playload = (JWTPlayloadInfo)Request.Properties["playload"];
            try
            {
                //验证各字段合法性
                string msg = "";
                bool isOk = _instance.VerifyModel(model, ref msg);
                if (isOk)
                {
                    bool res = _instance.AddPurchasePayApply(model);
                    if (res)
                    {
                        // 更新文件信息
                        if (model.FileList != null && model.FileList.Count > 0)
                        {
                            UploadBll.Instance.Update(model.ID, model.FileList);
                        }
                        LogHelper.LogAction(playload, Constant.SysModule.PurchasePayApply, Constant.ActionEnum.Add, "新增付款申请");
                        return JsonHelper.SuccessJson("新增成功");
                    }
                    else
                    {
                        LogHelper.LogWarn(playload, Constant.SysModule.PurchasePayApply, Constant.ActionEnum.Add, "新增付款申请");
                        return JsonHelper.FailJson("新增失败");
                    }
                }
                else
                {
                    return JsonHelper.FailJson(msg);
                }
            }
            catch (Exception ex)
            {
                LogHelper.LogError(playload, ex, Constant.SysModule.PurchasePayApply, Constant.ActionEnum.Add, "新增付款申请");
                throw;
            }
        }

        /// <summary>
        /// 修改付款申请
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public HttpResponseMessage UpdatePurchasePayApply([FromBody] PurchasePayApplyHead model)
        {
            playload = (JWTPlayloadInfo)Request.Properties["playload"];
            if (model.ID <= 0)
            {
                return JsonHelper.ErrorJson("参数错误");
            }
            try
            {
                bool isExist = _instance.IsExist(" and ID=" + model.ID);
                if (!isExist)
                {
                    return JsonHelper.ErrorJson("不存在该数据");
                }
                //验证各字段合法性
                string msg = "";
                bool isOk = _instance.VerifyModel(model, ref msg);
                if (isOk)
                {
                    bool res = _instance.UpdatePurchasePayApply(model);
                    if (res)
                    {
                        // 更新文件信息
                        if (model.FileList != null && model.FileList.Count > 0)
                        {
                            UploadBll.Instance.Update(model.ID, model.FileList);
                        }
                        LogHelper.LogAction(playload, Constant.SysModule.PurchasePayApply, Constant.ActionEnum.Edit, "修改付款申请");
                        return JsonHelper.SuccessJson("修改成功");
                    }
                    else
                    {
                        LogHelper.LogWarn(playload, Constant.SysModule.PurchasePayApply, Constant.ActionEnum.Edit, "修改付款申请");
                        return JsonHelper.FailJson("修改失败");
                    }
                }
                else
                {
                    return JsonHelper.FailJson(msg);
                }
            }
            catch (Exception ex)
            {
                LogHelper.LogError(playload, ex, Constant.SysModule.PurchasePayApply, Constant.ActionEnum.Edit, "修改付款申请");
                throw;
            }
        }

        /// <summary>
        /// 删除付款申请（状态为2：暂存时才可删除）
        /// </summary>
        /// <param name="id">ID</param>
        /// <returns></returns>
        [HttpPost]
        public HttpResponseMessage DeletePurchasePayApply(int id)
        {
            playload = (JWTPlayloadInfo)Request.Properties["playload"];
            try
            {
                if (id <= 0)
                {
                    return JsonHelper.FailJson("参数错误！");
                }
                else
                {
                    // 判断状态（状态为2：暂存时才可删除）
                    if (!_instance.IsExist(" and ID=" + id + " and PPA_AuditStatus=2 "))
                    {
                        return JsonHelper.FailJson("该付款申请正在使用中，不允许删除！");
                    }
                    else
                    {
                        bool result;
                        // 先删除相关图片
                        DataTable dt = UploadBll.Instance.GetFiles(id, "PurchasePayApply");
                        if (dt.Rows.Count > 0)
                        {
                            List<FileData> files = CommonOperation.ConvertDataTableToModelList<FileData>(dt);
                            string fid = "";
                            for (int i = 0; i < files.Count; i++)
                            {
                                if (string.IsNullOrEmpty(fid))
                                {
                                    fid = "'" + files[i].RelationId + "'";
                                }
                                else
                                {
                                    fid += ",'" + files[i].RelationId + "'";
                                }
                            }
                            bool res = UploadBll.Instance.DeleteFiles(fid, "PurchasePayApply", files);
                            if (res)
                            {
                                LogHelper.LogAction(playload, Constant.SysModule.PurchasePayApply, Constant.ActionEnum.Delete, "删除所有文件(HeadID:" + id + ")");
                                result = _instance.DeletePurchasePayApply(id);
                                if (result)
                                {
                                    LogHelper.LogAction(playload, Constant.SysModule.PurchasePayApply, Constant.ActionEnum.Delete, "删除付款申请");
                                    return JsonHelper.SuccessJson("删除成功");
                                }
                                else
                                {
                                    LogHelper.LogWarn(playload, Constant.SysModule.PurchasePayApply, Constant.ActionEnum.Delete, "删除付款申请");
                                    return JsonHelper.SuccessJson("删除失败");
                                }
                            }
                            else
                            {
                                LogHelper.LogWarn(playload, Constant.SysModule.PurchasePayApply, Constant.ActionEnum.Delete, "删除所有文件(HeadID:" + id + ")");
                                return JsonHelper.FailJson("删除文件失败");
                            }
                        }
                        else
                        {
                            result = _instance.DeletePurchasePayApply(id);
                            if (result)
                            {
                                LogHelper.LogAction(playload, Constant.SysModule.PurchasePayApply, Constant.ActionEnum.Delete, "删除付款申请");
                                return JsonHelper.SuccessJson("删除成功");
                            }
                            else
                            {
                                LogHelper.LogWarn(playload, Constant.SysModule.PurchasePayApply, Constant.ActionEnum.Delete, "删除付款申请");
                                return JsonHelper.SuccessJson("删除失败");
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.LogError(playload, ex, Constant.SysModule.PurchasePayApply, Constant.ActionEnum.Delete, "删除付款申请");
                throw;
            }
        }

        /// <summary>
        /// 修改审核状态
        /// </summary>
        /// <param name="id"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        [HttpPost]
        public HttpResponseMessage UpdateStatus(int id, int status)
        {
            playload = (JWTPlayloadInfo)Request.Properties["playload"];
            if (id <= 0)
            {
                return JsonHelper.ErrorJson("参数错误");
            }

            if (status != 1 && status != 2 && status != 0)
            {
                return JsonHelper.ErrorJson("参数错误");
            }

            string strStatus = "";

            if (status == 0)
            {
                strStatus = "审批中";
            }
            if (status == 1)
            {
                strStatus = "审批通过";
            }
            if (status == 2)
            {
                strStatus = "暂存";
            }

            try
            {
                // 判断是否存在该记录
                PurchasePayApplyHead model = _instance.GetModelById(id);
                if (model == null)
                {
                    return JsonHelper.ErrorJson("数据不存在，请刷新重试");
                }
                if (model.PPA_AuditStatus == 1)
                {
                    return JsonHelper.ErrorJson("该单据已审核通过");
                }

                int result = _instance.UpdateStatus(id, status);
                if (result > 0)
                {
                    LogHelper.LogAction(playload, Constant.SysModule.PurchaseOrder, Constant.ActionEnum.Edit, strStatus);
                    return JsonHelper.SuccessJson("状态修改成功");
                }
                else
                {
                    LogHelper.LogWarn(playload, Constant.SysModule.PurchaseOrder, Constant.ActionEnum.Edit, strStatus);
                    return JsonHelper.FailJson("状态修改失败");
                }
            }
            catch (Exception ex)
            {
                LogHelper.LogError(playload, ex, Constant.SysModule.PurchaseOrder, Constant.ActionEnum.Edit, strStatus);
                throw;
            }
        }

        #region 上传文件相关

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <returns></returns>
        public HttpResponseMessage UploadFile()
        {
            JWTPlayloadInfo playload = (JWTPlayloadInfo)Request.Properties["playload"];

            List<FileData> list = new List<FileData>();
            HttpFileCollection files = HttpContext.Current.Request.Files;
            foreach (var key in files.AllKeys)
            {
                HttpPostedFile postedFile = files[key];
                if (!string.IsNullOrEmpty(postedFile.FileName))
                {
                    // file.SaveAs(HttpContext.Current.Server.MapPath("~/imgcoll/") + file.FileName);
                    //文件扩展名，不含“.”
                    string fileExt = Utils.GetFileExt(postedFile.FileName);

                    // 文件类型
                    Regex regex = new Regex(@"pdf|doc|docx|xlsx|xls");
                    bool isMatch = regex.IsMatch(fileExt);
                    if (!isMatch)
                    {
                        return JsonHelper.ErrorJson("文件类型不匹配");
                    }

                    FileData model = UploadHelper.SaveFilePic(postedFile, UploadHelper.uploadPath + "files/pc/purchase/payApply/" + DateTime.Now.ToString("yyyyMMdd"), DateTime.Now.ToString("yyyyMMddHHmmss"));

                    // 文件类型
                    model.FileType = fileExt;

                    // 关联表
                    model.RelationTable = "PurchasePayApply";

                    if (model != null)
                    {
                        list.Add(model);
                    }
                    else
                    {
                        continue;
                    }
                }
            }
            if (list.Count > 0)
            {
                bool result = UploadBll.Instance.AddList(list);
                if (result)
                {
                    LogHelper.LogAction(playload, Constant.SysModule.PurchasePayApply, Constant.ActionEnum.Upload, "上传文件");
                    return JsonHelper.SuccessJson(JsonHelper.ListToJArray(list));
                }
                else
                {
                    LogHelper.LogWarn(playload, Constant.SysModule.PurchasePayApply, Constant.ActionEnum.Upload, "上传文件");
                    return JsonHelper.ErrorJson("上传失败，稍后重试");
                }
            }
            else
            {
                return JsonHelper.ErrorJson("没有匹配的文件类型");
            }
        }

        /// <summary>
        /// 根据文件ID删除文件
        /// </summary>
        /// <param name="fileID">文件ID</param>
        /// <returns></returns>
        [HttpPost]
        public HttpResponseMessage DeletePic(string fileID)
        {
            JWTPlayloadInfo playload = (JWTPlayloadInfo)Request.Properties["playload"];
            if (string.IsNullOrEmpty(fileID))
            {
                return JsonHelper.ErrorJson("参数错误");
            }
            FileData model = UploadBll.Instance.GetFileByID(fileID);
            if (model != null)
            {
                bool res = UploadBll.Instance.DeleteFilesByID(fileID, model);
                if (res)
                {
                    LogHelper.LogAction(playload, Constant.SysModule.PurchasePayApply, Constant.ActionEnum.Delete, "删除文件(ID:" + fileID + ")");
                    return JsonHelper.SuccessJson("删除成功！");
                }
                else
                {
                    LogHelper.LogWarn(playload, Constant.SysModule.PurchasePayApply, Constant.ActionEnum.Delete, "删除文件(ID:" + fileID + ")");
                    return JsonHelper.FailJson("删除失败！");
                }
            }
            else
            {
                return JsonHelper.FailJson("参数错误！,文件不存在");
            }
        }

        #endregion 上传文件相关

    }
}
